package com.xforceplus.bsstool.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.xforceplus.bsstool.config.ConfigMain;
import com.xforceplus.bsstool.db.NewUcenterDB;
import com.xforceplus.bsstool.db.OldUcenterDB;
import com.xforceplus.bsstool.log.LogMain;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServiceStep2 {

  /**
   * 获取老运营资源码认证服务关联关系列表
   * @return
   */
  public static List<Map> getOldResourceApiRelList(LogMain logger) throws Exception {
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_resource_api_rel t where t.resource_id "
            +"in(select resource_id from sys_resourceset_resource_rel  "
            +"where resourceset_id   ").append(ServiceCommon.getResourceSetIdInSql()).append(")");
    logger.info("执行老运营资源码认证服务关联关系获取，执行SQL: "+sql.toString());
    return OldUcenterDB.getSqlResult(sql.toString());
  }
  /**
   * 获取新运营资源码认证服务关联关系列表
   * @return
   */
  public static Map<String,Map> getNewResourceApiRelMap(LogMain logger) throws Exception {
    Map<String,Map> newResourceApiRelMapMap  = new HashMap<>();
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_resource_api_rel t where t.resource_id "
            +"in(select resource_id from sys_resourceset_resource_rel  "
            +"where resourceset_id   ").append(ServiceCommon.getResourceSetIdInSql()).append(")");
    logger.info("执行新运营资源码认证服务关联关系获取，执行SQL: "+sql.toString());
    List<Map> newResourceApiRelList = NewUcenterDB.getSqlResult(sql.toString());
    for (Map newResourceApiRelMap : newResourceApiRelList){
      newResourceApiRelMapMap.put(String.valueOf(newResourceApiRelMap.get("id")),newResourceApiRelMap);
    }
    return newResourceApiRelMapMap;
  }

  /**
   * 比对新运营功能集
   * @return
   */
  public static boolean compareResourceApiRelWithNew(List<Map> oldResourceApiRelList,LogMain logger) throws Exception {
    boolean result = true;
    Map<String,Map> newResourceApiRelMapMap  = getNewResourceApiRelMap(logger);
    for (Map oldResourceApiRelMap : oldResourceApiRelList){
      System.out.println("开始执行资源码认证服务关联关系比对 资源码认证服务关联关系ID:"+oldResourceApiRelMap.get("id"));
      logger.info("开始执行资源码认证服务关联关系比对 资源码认证服务关联关系ID:"+oldResourceApiRelMap.get("id"));
      //查询新运营对应功能集
      Map newResourceApiRelMap =newResourceApiRelMapMap.get(String.valueOf(oldResourceApiRelMap.get("id")));
      if (newResourceApiRelMap == null){
        logger.warn("资源码认证服务关联关系ID:"+oldResourceApiRelMap.get("id")+" 等待迁移中...");
      }else {
        logger.info("新老运营存在相同资源码认证服务关联关系ID,继续执行数据信息比对 新运营资源码认证服务关联关系："+ JSON.toJSONString(newResourceApiRelMap));
        //新老数据比对： resource_id service_api_id
        result = ServiceCommon.compareMapValue(oldResourceApiRelMap,newResourceApiRelMap,
                Lists.newArrayList("resource_id","service_api_id"),
                "资源码认证服务关联关系ID:"+oldResourceApiRelMap.get("id"),
                logger);
      }

      //重复资源码认证服务关联关系检查
      List<Map> sameResourceApiRelList = NewUcenterDB.getSqlResult("select * from sys_resource_api_rel where id != "+oldResourceApiRelMap.get("id")
              +" and resource_id = '"+oldResourceApiRelMap.get("resource_id")+"'"
              +" and service_api_id = '"+oldResourceApiRelMap.get("service_api_id")+"'");
      if (!CollectionUtils.isEmpty(sameResourceApiRelList)){
        logger.error("老运营资源码认证服务关联关系ID:"+oldResourceApiRelMap.get("id")+" 新运营存在重复资源码认证服务关联关系记录个数："+sameResourceApiRelList.size());
        result = false;
      }
    }
    return result;
  }


  /**
   * 获取老运营服务API列表
   * @return
   */
  public static List<Map> getOldServiceApiList(LogMain logger) throws Exception {
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT * from sys_service_api t where t.service_api_id  ")
            .append("in(SELECT service_api_id from sys_resource_api_rel  where resource_id   ")
            .append("in(select resource_id from sys_resourceset_resource_rel  where resourceset_id   ")
            .append(ServiceCommon.getResourceSetIdInSql()).append("))");
    logger.info("执行老运营服务API获取，执行SQL: "+sql.toString());
    return OldUcenterDB.getSqlResult(sql.toString());
  }
  /**
   * 获取新运营服务API列表
   * @return
   */
  public static Map<String,Map> getNewServiceApiMap(LogMain logger) throws Exception {
    Map<String,Map> newServiceApiMapMap  = new HashMap<>();
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT * from sys_service_api t where t.service_api_id  ")
            .append("in(SELECT service_api_id from sys_resource_api_rel  where resource_id   ")
            .append("in(select resource_id from sys_resourceset_resource_rel  where resourceset_id   ")
            .append(ServiceCommon.getResourceSetIdInSql()).append("))");
    logger.info("执行新运营服务API获取，执行SQL: "+sql.toString());
    List<Map> newServiceApiList = NewUcenterDB.getSqlResult(sql.toString());
    for (Map newServiceApiMap : newServiceApiList){
      newServiceApiMapMap.put(String.valueOf(newServiceApiMap.get("service_api_id")),newServiceApiMap);
    }
    return newServiceApiMapMap;
  }

  /**
   * 比对新运营功能集
   * @return
   */
  public static boolean compareServiceApiWithNew(List<Map> oldServiceApiList,LogMain logger) throws Exception {
    boolean result = true;
    Map<String,Map> newServiceApiMapMap  = getNewServiceApiMap(logger);
    for (Map oldServiceApiMap : oldServiceApiList){
      System.out.println("开始执行服务API比对 服务APIID:"+oldServiceApiMap.get("service_api_id"));
      logger.info("开始执行服务API比对 服务APIID:"+oldServiceApiMap.get("service_api_id"));
      //查询新运营对应功能集
      Map newServiceApiMap =newServiceApiMapMap.get(String.valueOf(oldServiceApiMap.get("service_api_id")));
      if (newServiceApiMap == null){
        logger.warn("服务APIID:"+oldServiceApiMap.get("service_api_id")+" 等待迁移中...");
      }else {
        logger.info("新老运营存在相同服务APIID,继续执行数据信息比对 新运营服务API："+ JSON.toJSONString(newServiceApiMap));
        //新老数据比对： app_id   service_api_path   service_api_url  service_api_name status
        oldServiceApiMap.put("app_id", ConfigMain.APP_ID);
        result = ServiceCommon.compareMapValue(oldServiceApiMap,newServiceApiMap,
                Lists.newArrayList("app_id","service_api_path","service_api_url","service_api_name","status"),
                "服务APIID:"+oldServiceApiMap.get("service_api_id"),
                logger);
      }

      //重复服务API检查
      List<Map> sameServiceApiList = NewUcenterDB.getSqlResult("select * from sys_service_api where service_api_id != "+oldServiceApiMap.get("service_api_id")
              +" and app_id = "+ConfigMain.APP_ID
              +" and service_api_path = '"+oldServiceApiMap.get("service_api_path")+"'"
              +" and service_api_url = '"+oldServiceApiMap.get("service_api_url")+"'"
              +" and service_api_name = '"+oldServiceApiMap.get("service_api_name")+"'");
      if (!CollectionUtils.isEmpty(sameServiceApiList)){
        logger.error("老运营服务APIID:"+oldServiceApiMap.get("service_api_id")+" 新运营存在重复服务API记录个数："+sameServiceApiList.size());
        result = false;
      }

    }
    return result;
  }
}
